package com.netty.handler;

import java.util.concurrent.locks.LockSupport;

import com.alibaba.fastjson.JSON;
import com.netty.util.MessageBody;
import com.netty.util.MessageHeader;
import com.netty.util.NettyMessage;
import com.netty.util.WrapperResponseMessage;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.HttpContent;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.util.CharsetUtil;

import io.netty.util.ReferenceCountUtil;
import io.netty.util.internal.StringUtil;

/**
 * 客户端消息接收handler
 * @author hmm
 */
public class ClientMessageHandler extends SimpleChannelInboundHandler<Object> {
	
	private WrapperResponseMessage wrapper;
	private Thread thread;
	
	public void setWrapper(WrapperResponseMessage wrapper) {
		this.wrapper = wrapper;
	}

	public void setThread(Thread thread) {
		this.thread = thread;
	}

	@Override
	public void channelInactive(ChannelHandlerContext ctx) throws Exception {
		System.out.println(ctx.channel()+" channel break!"+ctx.channel().isActive());
		
	}

	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		System.out.println("channelActive");
	}
	
	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		super.exceptionCaught(ctx, cause);
		System.out.println(cause);
	}

	@Override
	public void userEventTriggered(ChannelHandlerContext ctx, Object evt)
			throws Exception {
		if(evt instanceof IdleStateEvent){
			System.out.println("准备发送心跳数据");
			ctx.writeAndFlush(buildMessage());
			
		}
	}

	@Override
	protected void channelRead0(ChannelHandlerContext ctx, Object content) throws Exception {
		try{
	        if (content instanceof HttpRequest) {
	        	HttpRequest request = (HttpRequest) content;
	            wrapper.setUri(request.uri());
	        }
			if(content instanceof HttpContent){
				HttpContent httpContent = (HttpContent)content;
				ByteBuf buf = httpContent.content();
				if(buf.isReadable()){
					String result = buf.toString(CharsetUtil.UTF_8);
					if(!StringUtil.isNullOrEmpty(result)){
						wrapper.setBody(result);
						LockSupport.unpark(this.thread);
					}
				}
			}
		}catch(Exception e){
			System.out.println(e);
		}finally{
//			ReferenceCountUtil.release(content);
		}
	}
	
	/**
	 * 构建心跳信息
	 * @return
	 */
	private String buildMessage(){
		NettyMessage message = new NettyMessage();
		MessageHeader header = new MessageHeader();
		MessageBody body = new MessageBody();
		message.setHeader(header);
		message.setBody(body);
		body.setIp("127.0.0.1");
		
		header.setCrcCode("chenmutime");
		header.setType(5);
		String messageBody = JSON.toJSONString(message);
		
		return messageBody;
	}
}
